<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Review & Rating Synthesis
 * @version 	1.0.2
 * @author 		Rukan <rukanhitokiri@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://www.zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
 
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../init.php');
include(dirname(__FILE__).'/ZadminGallery.php');
require_once(_PS_MODULE_DIR_.'zcustomerpoint/classes/ZcustomerPointObject.php');

global $cookie;
/**
 * lay tat ca comment hien thi chung 
 */
if (isset($_GET['comment'])) {
	$html = '
	<div id="commentsPhoto">
		<div class="zlistCommentsDiv"> 
		<ul class="zlistComments" id="zlistComments">
		';
		$html .= Zreview::getHtmlLiListComment($_GET['id'],1,Configuration::get('PL_PAGE_COMMENT'),$cookie->id_lang);
	$html .= '</ul>
	<script type="text/javascript">
		function loadView(valueViewPrevious){
			$.ajax({
					url: baseDir + \'modules/zgallery/zgallery-ajax.php\',
					async: true,
					data: \'&id='.$_GET['id'].'&valueViewPrevious=\'+valueViewPrevious,
					success: function(ret)
					{
						$(\'#titlePrevious\').remove();
						$(\'#zlistComments\').prepend(ret);
					}
				});
		}
	</script></div>';
	if (isset ($cookie->id_customer)) {
		$html.=	'<div class="addNewReview" ">
			<form action="" method="POST" class="std" id="sendreview" >
				<div class="error" id="zdisplayError" style="display:none;margin-top: 3px; padding-top: 2px; padding-bottom: 0pt; margin-bottom: 0px;"></div>
				<input type="hidden" name="id_zgallery_photo" id="id_zgallery_photo" value="'.$_GET['id'].'"/>
				<ul class="zgalleryBlockComment">
					<li class="zgalleryBlockComment">
						<textarea id="zsubmitComment" title="Write a comment..." cols="20" rows="3" style="width: 239px; height: 58px;" name="content" placeholder="Write a comment..." id="content"></textarea>
					</li>
				</ul>
			</form>
			<script type="text/javascript">
				$("textarea#zsubmitComment").keyup(function(e){
				    var code = (e.keyCode ? e.keyCode : e.which);
				 if(code == 13 && !e.shiftKey) { //Enter keycode
				    $comment = $.trim ($(\'#zsubmitComment\').val());
					if ($comment!="") {
						$(\'#zdisplayError\').hide();
						serializedData = $(\'#sendreview\').serialize();
						serializedData = serializedData.replace(/%0A/gi, "<br/>");
						$.ajax({
							url: baseDir + \'modules/zgallery/zgallery-ajax.php\',
							async: true,
							data: serializedData+\'&submitReview=1&comment2=\'+$comment,
							success: function(ret)
							{
								if (ret=="falseComment"){
									alert("Bạn không đủ điểm để bình luận.");
									return false;
								}else{
									$(\'.zlistComments\').append(ret);
									$(\'#zsubmitComment\').val("");
								}
								
							}
						});
					}
					else {
						$(\'#content\').focus();
					}
					return false;
				 }
				});
			</script>
			</div>
			</div>	
		';
	}
	else {
		$link = new LinkCore();
		$html.= '
		<script type="text/javascript">
			$("#login-comment").fancybox({
				"transitionIn" : "elastic",
				"transitionOut" : "elastic"
			}); 
		</script>
		<h3 align="center"> Bạn hãy đăng nhập để sử dụng được chức năng này!<br /><br /> Click <a id="login-comment" href="#frm-login-dialog"> Đăng nhập </a> hoặc <a href="'.$link->getPageLink('authentication.php?register=1', true).'", true)}"> Đăng ký </a></h3>';
	}
	echo $html;
}
/**
 * add them comment 
 */
if (isset($_GET['submitReview'])) {
	global $cookie;
	
	$Zreview = new Zreview ();
	$Zreview->ip_client = ($id_customer = (int)$cookie->id_customer) ? 0 : $_SERVER['REMOTE_ADDR'];
	$Zreview->id_customer = $cookie->id_customer;
	$Zreview->active=2;
	$_GET['ip_client'] = ($id_customer = (int)$cookie->id_customer) ? 0 : $_SERVER['REMOTE_ADDR'];
	$_GET['id_customer'] = ($cookie->id_customer==NULL)?0:$cookie->id_customer;
	$_GET['active'] = 1;
	$_GET['date_add'] = date('Y-m-d H:i:s');
	$customer = new Customer($cookie->id_customer);
	
	$_GET['content'] = str_replace('%0','<br/>',$_GET['content']);
	
	$nickname = $customer->username;  
	// check points to comment
	$checkPointsComment = ZcustomerPointObject::_checkPointsCustomer((int)$cookie->id_customer);
	if ($checkPointsComment){
		$result = Db::getInstance()->Execute('
			INSERT INTO `'._DB_PREFIX_.'zgallery_review` 
					(`id_zgallery_photo`, `nickname`,`active`, `date_add`, `id_customer`, `ip_client`) 
			VALUES 
					('.$_GET['id_zgallery_photo'].',"'.$nickname.'","'.$_GET['active'].'", 
					"'.$_GET['date_add'].'", '.$_GET['id_customer'].', "'.$_GET['ip_client'].'")
		');
		
		$id=Db::getInstance()->Insert_ID();
		$link = Zalbum::getAlbumCurrent ($_GET['id_zgallery_photo']);
		$languages = Language::getLanguages(false);
		foreach ($languages AS $language) {
			$result = Db::getInstance()->Execute('
				INSERT INTO `'._DB_PREFIX_.'zgallery_review_lang` (`id_zgallery_review`, `id_lang`, `content`) VALUES ('.$id.', '.(int)($language['id_lang']).', "'.$_GET['content'].'")
			');
		}
		
		// sub points when comment
		$pointsComment = Configuration::get('ZPOINTS_COMMENT');
		ZcustomerPointObject::_updatePointToCustomer((int)($_GET['id_customer']), $pointsComment, false);
		
		$nameAlbum = Zalbum::getNameAlbum ($_GET['id_zgallery_photo'],$cookie->id_lang);
		$html = '
			<li class="zitemComment">	
				<div class="zcommentContent">
					<a href="'.$link.'">
							<p>'.substr($nameAlbum,0,30).''.(strlen($nameAlbum)>30?'...':'').'</p>
						</a>
					<b>'.$nickname.'</b>
					<span class="zcommentBody">'.$_GET['content'].'</span>
					<div class="zcommentActions">
						<b>'.$_GET['date_add'].'</b>
					</div>
				</div>
			</li>
		';
		echo $html;
	}else{
		echo 'falseComment';
	}
}
/**
 * xu ly viec phan trang cho comment
 */
if (isset($_GET['valueViewPrevious'])) {
	$id = $_GET['id'];
	$p = $_GET['valueViewPrevious'];
	$html = Zreview::getHtmlLiListComment($id,$p,Configuration::get('PL_PAGE_COMMENT'),$cookie->id_lang);
	echo $html;
}
/**
 * xu ly like dislike khi nhan vao nut like
 */
if (isset($_GET['like'])) {
	$id = $_GET['id'];
	$id_album = $_GET['id_album'];
	$nb_like = Zphoto::getInfoPicture ($id,$cookie->id_customer);
	$random_lucky_member = $nb_like['random_lucky_member']; 
	$nb_like = $nb_like['nb_like'];
	$query = '
		SELECT * FROM '._DB_PREFIX_.'zgallery_photo_like WHERE id_customer='.$cookie->id_customer.' AND id_zgallery_photo='.$id.'
	';
	$results = Db::getInstance()->Executes($query);
	$kq = array ();
	if (sizeof($results)==0) {
		// check points to like
		$checkPointsLike = ZcustomerPointObject::_checkPointsCustomer((int)$cookie->id_customer, true);
		if ($checkPointsLike){
			$query = '
			INSERT INTO `'._DB_PREFIX_.'zgallery_photo_like` (`id_zgallery_photo`, `id_customer`) VALUES ('.$id.', '.$cookie->id_customer.')
			';
			Db::getInstance()->Execute($query);
			$kq[0] = 'like';
			$nb_like=$nb_like+1;
			Db::getInstance()->Execute('
				UPDATE '._DB_PREFIX_.'zgallery_album 
				SET nb_like = (nb_like+1)
				WHERE id_zgallery_album='.$id_album);
			$rsadas = Zphoto::randomLuckyMember ($cookie->id_customer,$random_lucky_member,$id);
			if ($rsadas==true)
				$kq[2] = 1;
			else 
				$kq[2] = 0;
			// sub points when comment
			$pointsLike = Configuration::get('ZPOINTS_LIKE');
			ZcustomerPointObject::_updatePointToCustomer((int)($cookie->id_customer), $pointsLike, false);
			$kq[3] = 0;  // enough like 
		}else {
			$kq[0] = 'klikec';
			$kq[2] = 0;
			$kq[3] = 1; // not enough to like
		}
	} else {
		$query = '
			DELETE FROM `'._DB_PREFIX_.'zgallery_photo_like` WHERE (`id_zgallery_photo`='.$id.') AND (`id_customer`='.$cookie->id_customer.')
		';
		Db::getInstance()->Execute($query);
		$nb_like=$nb_like-1;
		$kq[0] = 'dislike';
		Db::getInstance()->Execute('
			UPDATE '._DB_PREFIX_.'zgallery_album 
			SET nb_like = (nb_like-1)
			WHERE id_zgallery_album='.$id_album);
	}
	$kq[1] = $nb_like;
	$kq = implode (",",$kq);
	
	echo  $kq;
	Db::getInstance()->Execute('
		UPDATE `'._DB_PREFIX_.'zgallery_photo` SET `nb_like`='.($nb_like).' WHERE (`id_zgallery_photo`='.$id.')
	');
	
}

if (isset($_GET['getInfos'])) {
	$id = $_GET['id'];
	$id_customer = (!$id_customer = (int)$cookie->id_customer) ? false : (int)$cookie->id_customer;
	$photos = Zphoto::getListPhoto ($id,$cookie->id_lang,$id_customer);
	echo json_encode($photos);
}
// get info for album 
if (isset($_GET['getInfosAlbum'])) {
	$id = $_GET['id'];
	$id_photo= $_GET['id_photo'];
	$album = new Zalbum($id,$cookie->id_lang);
	echo $album->name; 
}
// get info for album 
if (isset($_GET['getViewPhoto'])) {
	$id_photo= $_GET['id_photo'];
	$id = $_GET['id'];
	$rs = Zphoto::increaseViewPhoto ($id_photo,$id);
	if ($rs==1) echo 'ok';
	else echo 'no';
}
// when scroll list album 
if (isset($_GET['scroll'])) {
	$s = $_GET['scroll'];
	$id_item = $_GET['id_item'];
	$id_ct = $_GET['id_ct'];
	$number = Zalbum::getNumberAlbums($id_item,$id_ct);
	if (($s-1)*20 > $number) {
		echo 'false';
		die ();
	}else {
		$albums = Zalbum::getAlbumsItem ($id_item,$id_ct,$cookie->id_lang,$s,20);
		$rs = '';
		foreach ($albums as $album) {
			$rs .= '<div class="album-block clearfix">
						<a alt="'.$album['description'].'" href="'.$album['link'].'">
							<img src="'.$album['linkImage'].'" class="img">
						</a>
						<div class="album-details">
							<a alt="'.substr($album['description'],0,240).'" href="'.$album['link'].'">
								<h5 class="album-title">'.$album['name'].'</h5>
							</a>
							<p>'.substr($album['description'],0,240).(strlen($album['description'])>240?'...':'').'</p>
							<div class="album-des clearfix">
								<span class="album-author">Bởi '.substr($album['author'],0,27).(strlen($album['author'])>27?'...':'').'</span>
								<span class="album-time">'.$album['date_add'].'</span>
								<span class="album-view">'.$album['nb_view'].' lượt xem</span>
								<span class="album-view">'.$album['nb_like'].' lượt like</span>
							</div>
						</div>
					</div>';
		}
		if ($number > ($s)*20)
			$rs.= '<div class="choAjax" id="choAjax"><img src="'.__PS_BASE_URI__.'modules/zgallery/img/loader.gif"></div>';
		echo $rs;
	}	
}